package com.persondemo.videoappliction.ui.duanzi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.DetilsBean;
import com.persondemo.videoappliction.bean.HFBean;
import com.persondemo.videoappliction.bean.PingLunBean;
import com.persondemo.videoappliction.bean.ZanCaiBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.net.BaseApi;
import com.persondemo.videoappliction.ui.adapter.DPdetilsAdapter;
import com.persondemo.videoappliction.ui.adapter.DetilsImgAdapter;
import com.persondemo.videoappliction.ui.adapter.PingLunAdapter;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.duanzi.contract.DetilsContract;
import com.persondemo.videoappliction.ui.duanzi.presenter.DetilsPresenter;
import com.persondemo.videoappliction.ui.image.ImageDetailsActivity;
import com.persondemo.videoappliction.utils.FalseClickListener;
import com.persondemo.videoappliction.utils.FalseClickListener02;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.PreferenceUtil;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.widget.CustomLoadMoreView;
import com.persondemo.videoappliction.widget.SimpleMultiStateView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by Administrator on 2018/4/20.
 */

public class DuanziDetilsActivity extends BaseActivity<DetilsPresenter> implements DetilsContract.View, View.OnClickListener {
    @BindView(R.id.sure_btn)
    Button sureBtn;
    @BindView(R.id.detils_edit)
    EditText detilsEdit;
    @BindView(R.id.yule_top)
    RelativeLayout yuleTop;
    @BindView(R.id.detilsdetils_recycle02)
    RecyclerView detilsdetilsRecycle02;
    @BindView(R.id.SimpleMultiStateView)
    com.persondemo.videoappliction.widget.SimpleMultiStateView SimpleMultiStateView;
    @BindView(R.id.mPtrFrameLayout)
    PtrClassicFrameLayout mPtrFrameLayout;
    CircleImageView detilsImgHead01;
    TextView detilsName01;
    TextView detilsTime01;
    TextView detilsComment;
    RecyclerView detilsdetilsRecycle01;
    JCVideoPlayerStandard detilsVideoplayer;
    TextView detilsTitle;
    ImageView ivPlay;
    TextView tvVideoduration;
    RelativeLayout detilsVideoRelate;
    TextView baseDianzan;
    LinearLayout dianzanLiner;
    TextView baseCai;
    LinearLayout caiLiner;
    TextView baseCollect;
    LinearLayout collectLiner;
    TextView basePinglun;
    LinearLayout commentLiner;
    @BindView(R.id.duanzidetils_back)
    ImageView duanzidetilsBack;
    private String id = "";
    private String imei = "";
    private int page = 1;
    private String comment = "";
    private DetilsImgAdapter detilsImgAdapter;
    private PingLunAdapter pingLunAdapter;

    List<String> list;
    List<PingLunBean.DataBean> dataBeanList;
    private static final String TYPE_01 = "1";//点赞
    private static final String TYPE_02 = "2";//踩
    private static final String TYPE_03 = "3";//收藏
    private static final String TYPE_04 = "4";//对评论点赞
    View headview, footview;
    private int pos = 0;
    private int type = 0;

    @Override
    public void onRetry() {

    }

    @Override
    public int getContentLayout() {
        return R.layout.module_fragment_duanzideitls;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void bindView(View view, Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            id = intent.getStringExtra("id");
            type = intent.getIntExtra("type", 0);
        }
        duanzidetilsBack.setOnClickListener(v -> finish());
        headview = LayoutInflater.from(this).inflate(R.layout.module_include_detils, null);
        footview = LayoutInflater.from(this).inflate(R.layout.item_foot, null);
        detilsImgHead01 = headview.findViewById(R.id.detils_img_head_01);
        detilsName01 = headview.findViewById(R.id.detils_name_01);
        detilsTime01 = headview.findViewById(R.id.detils_time_01);
        detilsComment = headview.findViewById(R.id.detils_comment);
        detilsdetilsRecycle01 = headview.findViewById(R.id.detilsdetils_recycle01);
        detilsVideoplayer = headview.findViewById(R.id.detils_videoplayer);
        detilsTitle = headview.findViewById(R.id.detils_title);
        ivPlay = headview.findViewById(R.id.iv_play);
        tvVideoduration = headview.findViewById(R.id.tv_videoduration);
        tvVideoduration = headview.findViewById(R.id.tv_videoduration);
        detilsVideoRelate = headview.findViewById(R.id.detils_video_relate);

        baseDianzan = headview.findViewById(R.id.base_dianzan);

        dianzanLiner = headview.findViewById(R.id.dianzan_liner);

        baseCai = headview.findViewById(R.id.base_cai);

        caiLiner = headview.findViewById(R.id.cai_liner);

        baseCollect = headview.findViewById(R.id.base_collect);

        collectLiner = headview.findViewById(R.id.collect_liner);

        basePinglun = headview.findViewById(R.id.base_pinglun);

        commentLiner = headview.findViewById(R.id.comment_liner);

        sureBtn.setOnClickListener(this);
        dianzanLiner.setOnClickListener(this);
        caiLiner.setOnClickListener(this);
        collectLiner.setOnClickListener(this);
        commentLiner.setOnClickListener(this);
        detilsdetilsRecycle01.setLayoutManager(new GridLayoutManager(DuanziDetilsActivity.this, 1));
        detilsImgAdapter = new DetilsImgAdapter(DuanziDetilsActivity.this, list, type);
        Log.i("lidaming", "type=" + type);
        detilsdetilsRecycle01.setAdapter(detilsImgAdapter);
        detilsImgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent i = new Intent(DuanziDetilsActivity.this, ImageDetailsActivity.class);
                i.putStringArrayListExtra("list_img", (ArrayList<String>) list);
                startActivity(i);
            }
        });
        detilsImgAdapter.setLoadMoreView(new CustomLoadMoreView());
        detilsImgAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        detilsdetilsRecycle02.setLayoutManager(new GridLayoutManager(DuanziDetilsActivity.this, 1));
        detilsdetilsRecycle02.setNestedScrollingEnabled(false);
        pingLunAdapter = new PingLunAdapter(dataBeanList, DuanziDetilsActivity.this);
        detilsdetilsRecycle02.setAdapter(pingLunAdapter);
        pingLunAdapter.setEnableLoadMore(true);
        pingLunAdapter.setLoadMoreView(new CustomLoadMoreView());
        pingLunAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        pingLunAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        pingLunAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (FalseClickListener.isFastDoubleClick()) {
                    T.showShort(DuanziDetilsActivity.this, "你已点过赞了，请勿重复点击！");
                    return;
                } else {
                    pos = position;
                    if (mPresenter != null) {
                        mPresenter.zancaiping(dataBeanList.get(position).getId() + "", TYPE_04, imei);
                    }
                }

            }
        });
        pingLunAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.getpinlun(id, page + "");
            }
        }, detilsdetilsRecycle02);

        mPtrFrameLayout.disableWhenHorizontalMove(true);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, detilsdetilsRecycle02, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                if (mPresenter != null) {
                    mPresenter.getpinlun(id, page + "");
                }
            }
        });

        detilsEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length()==25) {{
                    T.showShort(DuanziDetilsActivity.this,"最多输入25个字！");
                }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    public void initData() {

        list = new ArrayList<>();
        dataBeanList = new ArrayList<>();

        if (mPresenter != null) {
            showLoadingDialog();
            mPresenter.getdata(id);
            mPresenter.getpinlun(id, page + "");
        }
        //禁止输入框enter换行
        detilsEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    @Override
    public void showFaild() {
        super.showFaild();
        T.showLong(DuanziDetilsActivity.this, "加载失败！");
    }

    @Override
    public void loaddata(DetilsBean detilsBean) {
        hideLoadingDialog();
        if (detilsBean != null && detilsBean.getStatus() == 1) {
            ImageLoaderUtil.LoadImagelarge(DuanziDetilsActivity.this, detilsBean.getData().getAvatar(), detilsImgHead01);
            baseDianzan.setText(detilsBean.getData().getSupport() + "");
            baseCai.setText(detilsBean.getData().getOpposition() + "");
            baseCollect.setText(detilsBean.getData().getShou() + "");
            basePinglun.setText(detilsBean.getData().getPing() + "");
            detilsName01.setText(detilsBean.getData().getUsername());
            detilsTime01.setText(detilsBean.getData().getTime());
            if (!TextUtils.isEmpty(detilsBean.getData().getVideo())) {
                detilsVideoplayer.setUp(detilsBean.getData().getVideo()
                        , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, detilsBean.getData().getContent());
                detilsVideoRelate.setVisibility(View.VISIBLE);
                ImageLoaderUtil.LoadImagelarge(DuanziDetilsActivity.this, detilsBean.getData().getVideo_img(), detilsVideoplayer.thumbImageView);
                return;
            }
            if (detilsBean.getData().getImgs() != null && detilsBean.getData().getImgs().size() > 0) {
                detilsComment.setText(detilsBean.getData().getContent());
//                detilsdetilsRecycle01.setVisibility(View.VISIBLE);
//                detilsComment.setVisibility(View.VISIBLE);
                detilsVideoRelate.setVisibility(View.GONE);
                list = detilsBean.getData().getImgs();
                detilsImgAdapter.setNewData(list);
                showSuccess();
                return;
            }
            if (TextUtils.isEmpty(detilsBean.getData().getVideo()) && detilsBean.getData().getImgs().size() == 0) {
                detilsVideoRelate.setVisibility(View.GONE);
                detilsdetilsRecycle01.setVisibility(View.GONE);
                detilsComment.setText(detilsBean.getData().getContent());
//                detilsComment.setVisibility(View.VISIBLE);
            }
        } else {
            showFaild();
        }
    }

    @Override
    public void loadpinlundata(PingLunBean pingLunBean) {
        hideLoadingDialog();
        if (pingLunBean.getData() != null && pingLunBean.getStatus() == 1) {
            dataBeanList.clear();
            pingLunAdapter.removeAllHeaderView();
            pingLunAdapter.removeAllFooterView();
            dataBeanList = pingLunBean.getData();
            pingLunAdapter.setNewData(dataBeanList);
            pingLunAdapter.addHeaderView(headview);
            page++;
            mPtrFrameLayout.refreshComplete();
            if (dataBeanList.size() < 8) {
                pingLunAdapter.loadMoreEnd();
                pingLunAdapter.addFooterView(footview);
            }
            showSuccess();
        } else {
            showFaild();
        }
    }

    @Override
    public void pinlunmore(PingLunBean pingLunBean) {
        if (pingLunBean.getData() == null || pingLunBean.getData().size() == 0) {
            pingLunAdapter.loadMoreEnd();
            T.showLong(DuanziDetilsActivity.this, "没有更多的数据了！");
            return;
        } else {
            page++;
            pingLunAdapter.addData(pingLunBean.getData());
            pingLunAdapter.loadMoreComplete();
        }
    }

    @Override
    public void getzcp(ZanCaiBean zanCaiBean) {
        if (zanCaiBean.getStatus() == 1) {
            if (zanCaiBean.getData().getType().equals("1")) {
                baseDianzan.setText(zanCaiBean.getData().getNum() + "");
            } else if (zanCaiBean.getData().getType().equals("2")) {
                baseCai.setText(zanCaiBean.getData().getNum() + "");
            } else if (zanCaiBean.getData().getType().equals("3")) {
                baseCollect.setText(zanCaiBean.getData().getNum() + "");
            } else {
                if (dataBeanList.size() == 0) {
                    PingLunBean.DataBean pingLunBean = new PingLunBean.DataBean();
                    pingLunBean.setPraise(zanCaiBean.getData().getNum());

                } else {
                    PingLunBean.DataBean dataBean = dataBeanList.get(pos);
                    dataBean.setPraise(zanCaiBean.getData().getNum());
//                    pingLunAdapter.notifyItemChanged(pos);
                    pingLunAdapter.removeAllFooterView();
                    pingLunAdapter.notifyDataSetChanged();
                }
//

//                pingLunAdapter.notifyItemChanged(pos);
            }
        }
    }

    @Override
    public void getHF(HFBean hfBean) {
        hideLoadingDialog();
        if (hfBean.getStatus() == 1) {
            detilsEdit.setText("");
            closeKeyboard();
            if (dataBeanList.size() == 0) {
                PingLunBean.DataBean pingLunBean = new PingLunBean.DataBean();
                pingLunBean.setContent(comment);
                pingLunBean.setPraise(0);
                String avatar = PreferenceUtil.getString("avatar", "");
                if (!TextUtils.isEmpty(avatar)) {
                    pingLunBean.setAvatar(BaseApi.sIFengApi + avatar);
                }
                String username = PreferenceUtil.getString("username", "");
                if (TextUtils.isEmpty(username)) {
                    pingLunBean.setUsername("无名氏");
                } else {
                    pingLunBean.setUsername(username);
                }
                dataBeanList.add(pingLunBean);
                pingLunAdapter.removeAllFooterView();
                pingLunAdapter.notifyItemChanged(dataBeanList.size());
            } else {
                PingLunBean.DataBean dataBean = dataBeanList.get(dataBeanList.size() - 1);
                dataBean.setContent(comment);
                dataBean.setPraise(0);
                String avatar = PreferenceUtil.getString("avatar", "");
                if (!TextUtils.isEmpty(avatar)) {
                    dataBean.setAvatar(BaseApi.sIFengApi + avatar);
                }
                String username = PreferenceUtil.getString("username", "");
                if (TextUtils.isEmpty(username)) {
                    dataBean.setUsername("无名氏");
                } else {
                    dataBean.setUsername(username);
                }
                dataBeanList.add(dataBean);
                pingLunAdapter.removeAllFooterView();
                pingLunAdapter.notifyItemChanged(dataBeanList.size());
            }
        } else {
            T.showShort(DuanziDetilsActivity.this, hfBean.getMsg());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

    }


    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @Override
    public void onClick(View v) {
        imei = PreferenceUtil.getString("imei", "");
        Log.i("lidaming", "imei" + imei);
        if (TextUtils.isEmpty(imei)) {
            T.showLong(DuanziDetilsActivity.this, "你还未登录，请同意获取手机权限imei,如果拒绝，请前往手机设置获取权限！");
            return;
        }
        switch (v.getId()) {
            case R.id.dianzan_liner:
                if (FalseClickListener.isFastDoubleClick()) {
                    T.showShort(DuanziDetilsActivity.this, "你点击过于频繁，请勿重复点击！");
                    return;
                }
                if (mPresenter != null) {
                    mPresenter.zancaiping(id, TYPE_01, imei);
                }
                break;
            case R.id.cai_liner:
                if (FalseClickListener02.isFastDoubleClick()) {
                    T.showShort(DuanziDetilsActivity.this, "你点击过于频繁，请勿重复点击！");
                    return;
                }
                if (mPresenter != null) {
                    mPresenter.zancaiping(id, TYPE_02, imei);
                }
                break;
            case R.id.collect_liner:

                if (mPresenter != null) {
                    mPresenter.zancaiping(id, TYPE_03, imei);
                }
                break;
            case R.id.sure_btn:
                if (TextUtils.isEmpty(detilsEdit.getText().toString())) {
                    T.showShort(DuanziDetilsActivity.this, "内容不能为空！");
                    return;
                }
                if (mPresenter != null) {
                    showLoadingDialog();
                    comment = detilsEdit.getText().toString();
                    mPresenter.getHf(id, detilsEdit.getText().toString(), imei, "");
                }
                break;
        }
    }

    /**
     * EditText获取焦点并显示软键盘
     */

    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    private void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


}
